<template>
  <div>
    <form action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <van-swipe-cell :name="item.id" :before-close="beforeClose" v-for="item in list" :key="item.id" v-show="display">
      <van-cell :border="false" :title="item.name" :value="'商品上架时间：'+item.ctime.substr(0,10)"/>
      <template #right>
        <van-button square type="danger" text="删除" />
      </template>
    </van-swipe-cell>
    <div v-show="!display">
      <van-row type="flex" justify="space-around">
        <van-col span="20">搜索历史</van-col>
        <van-col span="1"><van-icon name="delete" @click="delHistoryList" /></van-col>
      </van-row>
      <div class="tag_list"><van-tag v-for="(item,i) in historyList" :key="i" @click="clicktag(item)">{{item}}</van-tag></div>  
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: "",//搜索输入值
      list: [],//搜索列表
      display: false, //搜索列表显示隐藏
      historyList: []
    };
  },

  created() {
    this.getLocalStorage()
  },

  methods: {
    // 获取搜索列表
    async getSearchList(){
      const { data:res } = await this.$axios.get('/api/getprodlist')
      this.list = res.message
    },
    // 点击搜索和回车键触发
    onSearch(val) {
      this.display=true
      let arr=this.getLocalStorage()
      if(arr.indexOf(val)==-1)
      {
        arr.push(val)
        this.setLocalStorage(arr)
      }
      this.getSearchList()
    },
    // 点击取消触发
    onCancel() {
      this.display=false
    },
    // 触发右侧删除
    // position 为关闭时点击的位置
    // instance 为对应的 SwipeCell 实例
    beforeClose({ position, instance }) {
      if(position=="right")
      {
          this.$dialog.confirm({
            message: '确定删除吗？'
          }).then(async () => {
            const { data:res }=await this.$axios.get(`/api/delproduct/${instance.name}`)
            if(res.status!=0) return this.$notify('删除失败')
            this.$notify({type:"success",message:"删除成功"})
            this.getSearchList()
          });
      }
    },
    //设置缓存
    setLocalStorage(arr){
      localStorage.setItem('historySearch',JSON.stringify(arr))
    },
    //获取缓存
    getLocalStorage(){
      this.historyList= JSON.parse(localStorage.getItem('historySearch')||"[]")
      return this.historyList
    },
    // 删除搜索缓存
    delHistoryList(){
      this.historyList=[]
      this.setLocalStorage([])
    },
    //点击标签赋值给搜索框
    clicktag(val){
     this.value=val
    }
    
  }
};
</script>

<style scoped lang='less'>
/deep/.van-cell{
  padding: 10px 5px;
}
.tag_list{
  padding: 5px 15px;
  span{
    margin-right: 10px;
    font-size: 12px;
  }
}
.van-row{
  padding: 10px 0;
}
</style>
